package com.topc.code.api;

import com.topc.base.api.CommonResult;
import com.topc.base.exception.Asserts;
import com.topc.code.service.ICodeRunService;
import com.topc.problem.model.code.CommitCodeResult;
import com.topc.problem.model.code.ExecuteCodeResponse;
import com.topc.problem.model.code.JudgeCompileInfo;
import com.topc.problem.model.dto.SaveProblemCommitDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/close")
public class CodeCloseController {

    @Autowired
    private ICodeRunService codeRunService;

    private final Semaphore semaphore = new Semaphore(16);

    //调试代码，运行代码程序，返回输出结果，不存到数据库(禁用)
//    @PostMapping("/debug")
//    public CommonResult<ExecuteCodeResponse> debugCode(@RequestBody JudgeCompileInfo judgeCompileInfo ){
//        ExecuteCodeResponse result = codeRunService.codeDebug(judgeCompileInfo);
//        return CommonResult.success(result);
//    }


    //运行代码，运行代码程序，提交记录到数据库，返回输出结果
    @PostMapping("/run")
    public CommonResult<Long> runCode(@RequestBody SaveProblemCommitDto saveProblemCommitDto){
        Long problemUserMidId = null;
        try {
            semaphore.acquire(); // 获取信号量
            problemUserMidId = codeRunService.codeRun(saveProblemCommitDto);
        } catch (InterruptedException e) {
            System.out.println("访问人数过多，无法执行");
            Thread.currentThread().interrupt(); // 处理线程中断
            Asserts.fail("进程访问人数较多，请稍后再试");
        } finally {
            semaphore.release(); // 释放信号量
        }
        return CommonResult.success(problemUserMidId);
    }

    //查看当前判题结果(题目提交界面)
    @GetMapping("/search-commit-result")
    public CommonResult<CommitCodeResult> searchCodeResult(Long problemUserMidId){
        CommitCodeResult codeResponse=null;
        try {
            semaphore.acquire(); // 获取信号量
            codeResponse = codeRunService.getCodeResponse(problemUserMidId);
        } catch (InterruptedException e) {
            System.out.println("访问人数过多，无法执行");
            Thread.currentThread().interrupt(); // 处理线程中断
            Asserts.fail("进程访问人数较多，请稍后再试");
        } finally {
            semaphore.release(); // 释放信号量
        }
        return CommonResult.success(codeResponse);
    }

}
